package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class BehaviorAdvice {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")
    public Object saveBehaviorToRedis(ProceedingJoinPoint pjp ){

        Object proceed = null;
        try {

//        获取方法签名：当前方法对象和方法中的参数
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            Method method = signature.getMethod();
            String name = method.getName();

            if(name.startsWith("save")){

               log.error("0000000000000000执行了"+name+"方法00000000000000000000");
                //        获取方法名
                BehaviorDto dto = (BehaviorDto) pjp.getArgs()[0];
    //        获取当前方法的参数（当前登录人  文章作者  当前文章ID）都可以从BehaviorDto
    //        向Redis中添加或删除标记数据
    //        关注  点赞 不喜欢  收藏

    //            0  关注 点赞 不喜欢 收藏    1 取消关注 取消点赞 取消不喜欢 取消收藏
                Integer operation = dto.getOperation();
                if(operation==0){
                    redisTemplate.boundValueOps(name+"_"+ dto.getUserId()+"_"+dto.getAuthorId()+"_"+dto.getArticleId()+"_"+dto.getEquipmentId()).set("");
                }else{
                    redisTemplate.delete(name+"_"+ dto.getUserId()+"_"+dto.getAuthorId()+"_"+dto.getArticleId()+"_"+dto.getEquipmentId());
                }
            }

            proceed = pjp.proceed(); //执行原方法

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;

    }


}
